package com.example.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.common.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;


@Component
//自定义异常处理类，实现BlockExceptionHandler接口,专门处理web资源的的异常
public class MyWebException implements BlockExceptionHandler {

    //转化为json数据的工具类
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String s, BlockException e) throws Exception {

        //设置响应的内容类型，支持utf-8编码
        httpServletResponse.setContentType("text/html;charset=utf-8");
        //设置响应的状态码，429通常表示请求被限流
        httpServletResponse.setStatus(429);
        //获取响应的输出流，写入自己定义的异常信息
        PrintWriter writer = httpServletResponse.getWriter();


        R error = R.error(500, "请求被限流了,原因：" + e.getMessage());
        //将R对象转化为json字符串
        String json = objectMapper.writeValueAsString(error);

        //write方法，写入到响应体中
        writer.write(json);

    }
}
